<template>
  <div class="cms-ads-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>广告管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增广告
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="广告图片" width="150" align="center">
          <template #default="{ row }">
            <el-image :src="row.image" fit="cover" style="width: 120px; height: 60px" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="广告标题" width="180" />
        <el-table-column prop="position" label="广告位置" width="120" align="center">
          <template #default="{ row }">
            <el-tag>{{ getPositionName(row.position) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="链接地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="clickCount" label="点击数" width="100" align="center" sortable />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入广告标题" />
        </el-form-item>
        <el-form-item label="广告位置" prop="position">
          <el-select v-model="form.position" placeholder="请选择广告位置" style="width: 100%">
            <el-option label="首页顶部" value="home-top" />
            <el-option label="首页侧边" value="home-side" />
            <el-option label="文章页顶部" value="article-top" />
            <el-option label="文章页底部" value="article-bottom" />
            <el-option label="列表页侧边" value="list-side" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" prop="image">
          <el-upload
            class="ad-uploader"
            :show-file-list="false"
            action="#"
            :auto-upload="false"
          >
            <img v-if="form.image" :src="form.image" class="ad-image" />
            <el-icon v-else class="ad-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-text size="small" type="info">建议尺寸：800x400像素</el-text>
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input v-model="form.url" placeholder="点击广告后跳转的地址" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="打开方式">
          <el-radio-group v-model="form.target">
            <el-radio value="_blank">新窗口</el-radio>
            <el-radio value="_self">当前窗口</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增广告')
const formRef = ref()

const form = reactive({
  id: null,
  title: '',
  position: '',
  image: '',
  url: '',
  startTime: '',
  endTime: '',
  target: '_blank',
  status: 1,
  remark: ''
})

const rules = {
  title: [{ required: true, message: '请输入广告标题', trigger: 'blur' }],
  position: [{ required: true, message: '请选择广告位置', trigger: 'change' }],
  image: [{ required: true, message: '请上传广告图片', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

const getPositionName = (position) => {
  const nameMap = {
    'home-top': '首页顶部',
    'home-side': '首页侧边',
    'article-top': '文章页顶部',
    'article-bottom': '文章页底部',
    'list-side': '列表页侧边'
  }
  return nameMap[position] || position
}

const handleAdd = () => {
  dialogTitle.value = '新增广告'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑广告'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除广告"${row.title}"吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

const handleStatusChange = (row) => {
  ElMessage.success(`已${row.status === 1 ? '启用' : '禁用'}广告：${row.title}`)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(form.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadData()
    }
  })
}

const loadData = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = [
      {
        id: 1,
        title: '首页轮播广告1',
        position: 'home-top',
        image: 'https://via.placeholder.com/800x400',
        url: 'https://example.com',
        startTime: '2024-10-01 00:00:00',
        endTime: '2024-12-31 23:59:59',
        clickCount: 256,
        status: 1,
        target: '_blank'
      },
      {
        id: 2,
        title: '侧边栏推广',
        position: 'home-side',
        image: 'https://via.placeholder.com/300x600',
        url: 'https://example.com',
        startTime: '2024-10-01 00:00:00',
        endTime: '2024-12-31 23:59:59',
        clickCount: 128,
        status: 1,
        target: '_blank'
      }
    ]
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cms-ads-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ad-uploader {
  width: 300px;
  height: 150px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}

.ad-uploader:hover {
  border-color: var(--el-color-primary);
}

.ad-image {
  width: 300px;
  height: 150px;
  object-fit: cover;
}

.ad-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

